package com.gtmc.gclub.chat.conimp;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gtmc.gclub.chat.bean.Result;
import com.gtmc.gclub.chat.constants.ChatConstant;
import com.gtmc.gclub.chat.jmessage.UserOperator;
import com.gtmc.gclub.chat.model.TrUserEnterprise;
import com.gtmc.gclub.chat.service.WxChatUserService;
import com.gtmc.gclub.chat.util.JmessageUserUtil;

@Service
public class WxControllerImpl {
	
	private static Logger logger = LoggerFactory.getLogger(WxControllerImpl.class);
	
	@Autowired
	private UserOperator userOperator;
	
	@Autowired
	private WxChatUserService wxChatUserService;
	
	public boolean registerJmessageCodeForChat(List<TrUserEnterprise> userInfos) {
		boolean updateFlag = false;
		TrUserEnterprise owner = userInfos.get(0);
		boolean pcjmessageRegisterFlag = true;
		boolean qyjmessageRegisterFlag = true;
		// 是否有jmessageCode
		if (StringUtils.isEmpty(owner.getJmessageCode())) {
			String pcjmessage = JmessageUserUtil.getPcJmessageCode(owner.getUserId());
			pcjmessageRegisterFlag = registerJmessageCode(pcjmessage,ChatConstant.JMESSAGE_DEFAULT_PWD);
			if(pcjmessageRegisterFlag) {
				owner.setJmessageCode(pcjmessage);
				updateFlag = true;
				logger.debug("Jmessage账号注册成功 "+pcjmessage);
			}
		}
		if (StringUtils.isEmpty(owner.getWxJmessageCode())) {
			String qyjmessage = JmessageUserUtil.getQyJmessageCode(owner.getUserId());
			qyjmessageRegisterFlag = registerJmessageCode(qyjmessage,ChatConstant.JMESSAGE_DEFAULT_PWD);
			if(qyjmessageRegisterFlag) {
				owner.setWxJmessageCode(qyjmessage);
				updateFlag = true;
				logger.debug("Jmessage账号注册成功 "+qyjmessage);
			}
		}
		if (owner.getJmessageStatus()==null || owner.getJmessageStatus()!=1) {
			logger.debug("Jmessage上线"+owner.getJmessageCode());
			// 修改数据库
			owner.setJmessageStatus(1);
			updateFlag = true;
		}
		if(updateFlag) {
			if (wxChatUserService.updateChatInfo(owner) <= 0) {
				logger.error("Jmessage账号信息写入数据库失败："+owner);
			}else {
				logger.error("Jmessage账号信息写入数据库成功："+owner);
			}
		}
		return true;
	}
	private boolean registerJmessageCode(String jmessage,String pass) {
		Result<Map> pcregResult = userOperator.registerAdmins(jmessage, pass);
		if (pcregResult.getReturnFlag() != 1) {// 注册失败
			logger.error("Jmessage账号注册失败："+jmessage);
			return false;
		}
		return true;
	}
}
